package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 邓大帅
 * Date: 2024-01-28
 * Time: 7:26
 */
public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serverIp, int port) throws IOException {
        socket = new Socket(serverIp,port);
    }
    public void start() {
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            Scanner scannerFromServer = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true) {
                System.out.println("-> ");
                String request = scanner.next();
//                这里不会直接写网卡，而是输出到内存缓冲区，当缓冲区满了，再一次性写入网卡，缓冲区也可以手动刷新
//                控制台是行缓冲，网卡和硬盘是全缓冲
                writer.println(request);
                writer.flush();
                String response = scannerFromServer.next();
                System.out.printf("req: %s, res: %s\n", request, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }
}
